package org.zyj.io.example.case1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.concurrent.ExecutionException;

/**
 *
 */
public class Server1 {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        final NioEventLoopGroup bossGroup = new NioEventLoopGroup(); //默认是CPU核心数量乘以2
        final NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap //进行设置
                    .group(bossGroup, workGroup)//设置两个线程组
                    .channel(NioServerSocketChannel.class) //使用 NioServerSocketChannel 作为服务器的通道实现
                    //TCP 服务端用 NioServerSocketChannel
                    //TCP 客户端用 NioSocketChannel
                    //UDP 用 NioDatagramChannel
                    //Sctp 客户端用 NioSctpCHannel
                    //Sctp 服务端用 NioSctpServerChannel
                    //.....
                    .option(ChannelOption.SO_BACKLOG, 128)  //https://www.yuque.com/zhouyijin/ydt8po/hd833d
                    .option(ChannelOption.SO_KEEPALIVE, true) //设置保持活动连接状态
                    .handler(new LoggingHandler(LogLevel.INFO)) //
                    .childHandler(new ChannelInitializer<NioSocketChannel>() { //配置 pipeline
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            //入站的时候(就是接收数据的时候), 从上向下按顺序, InBound操作
                            ch.pipeline() //配置pipeline
                                    .addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(9998).sync();//已经启动服务器了
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()){
                        System.out.println("服务器启动: 端口监听成功");
                    }else {
                        System.out.println("服务器启动: 端口监听失败");
                    }

                }
            });
            //阻塞, 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
        }
    }
}